package com.sailboard.iot.opm.web.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.sailboard.iot.opm.common.JsonResult;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * oss测试
 */
@Controller
@RequestMapping("/demo")
public class DemoController {

    private static final Logger LOGGER = LoggerFactory.getLogger(DemoController.class);

    String endpoint = "oss-cn-beijing.aliyuncs.com";
    String accessId = "LTAI3zsFLe7kcDIP";
    String accessKey = "5YKln5mFKKHJcSfi8891yPKnQ9lnvJ";
    String bucket = "hbwl-static";
    String dir = "user-dir";
    String host = "http://" + bucket + "." + endpoint;

    @RequestMapping(value = "/aliyun/upload", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject upload() {
        OSSClient client = new OSSClient(endpoint, accessId, accessKey);

        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            java.sql.Date expiration = new java.sql.Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            //respMap.put("expire", formatISO8601Date(expiration));
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            net.sf.json.JSONObject ja1 = net.sf.json.JSONObject.fromObject(respMap);
            System.out.println(ja1.toString());
            return ja1;

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 上传成功回调方法
     * @param request
     * @return
     */
    @RequestMapping(value = "callback",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult callback(HttpServletRequest request) {
        com.alibaba.fastjson.JSONObject data = new com.alibaba.fastjson.JSONObject();
        String filename = request.getParameter("filename");
        filename = "http://".concat(bucket).concat(".").concat(endpoint).concat("/").concat(filename);
        data.put("filename", filename);
        data.put("size", request.getParameter("size"));
        data.put("mimeType", request.getParameter("mimeType"));
        data.put("width", request.getParameter("width"));
        data.put("height", request.getParameter("height"));
        return  JsonResult.success();
    }


    @RequestMapping(value = "/toup", method = RequestMethod.GET)
    public ModelAndView test(HttpServletRequest request) {
        OSSClient client = new OSSClient(endpoint, accessId, accessKey);
        com.alibaba.fastjson.JSONObject result = new com.alibaba.fastjson.JSONObject();
        // 存储目录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dir = sdf.format(new Date());
        // 签名有效期
        long expireEndTime = System.currentTimeMillis() + 12 * 1000*1000;
        Date expiration = new Date(expireEndTime);
        // 文件大小
        long maxSize = 10 * 1024 * 1024;
        // 回调
        com.alibaba.fastjson.JSONObject callback = new com.alibaba.fastjson.JSONObject();
        callback.put("callbackUrl", "http://iot.com/demo/callback");
        callback.put("callbackBody", "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
        callback.put("callbackBodyType", "application/x-www-form-urlencoded");
        // 提交节点
        String action = "http://" + bucket + "." + endpoint;
        try {
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, maxSize);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String policy = BinaryUtil.toBase64String(binaryData);
            String signature = client.calculatePostSignature(postPolicy);
            String callbackData = BinaryUtil.toBase64String(callback.toString().getBytes("utf-8"));
            // 返回结果
            result.put("OSSAccessKeyId", client.getCredentialsProvider().getCredentials().getAccessKeyId());
            result.put("policy", policy);
            result.put("signature", signature);
            result.put("dir", dir);
            result.put("callback", callbackData);
            result.put("action", action);
            result.put("endpoint", "http://"+endpoint);
        } catch (Exception e) {
            LOGGER.error("签名生成失败", e);
        }
        ModelAndView modelAndView= new ModelAndView("index");
        modelAndView.addObject("policy", result);
        return modelAndView;   
    }

}
